import QtQuick 2.0


/* 实验运行信息展示、筛选控制 */

/* 传入: 设备Id */
/* 通过设备Id当前设备状态，显示结果 */
Rectangle {

    id: root

    property var pageList: ({})       // 记录每个equ在实时图谱还是曲线图谱
    property int currentPage: 0       // 当前设备是实时图谱还是曲线图谱
    onCurrentPageChanged: {
        console.log("设备"+equId+"记录页面"+currentPage)
        pageList[equId] = currentPage
    }

    signal experimentEnd()

    // Public ============================================================================

    function initEquPage(eid){     // 新建实验时调用，EquId清空至1
        console.log("initEquPage", eid)
        pageList[eid] = 0
    }

    // 设置设备Id
    function setEquId(eid){
        console.log("RUNNING DISPLAY - SET_EQU_ID:", eid)
        equId = eid
        currentPage = pageList[equId]

        // 切换设备Id时，更新状态
        if(equId === "3" || CSetUp.queryEquInfo()[equId]["EquStatus"].toString() === "2"){
//            console.log("RunningDisplay: 设备运行中")
            timer.restart()
        }else{
            timer.stop()
            return
        }

        // 更新筛选状态

        accessFilter = ["FAM", "VIC", "CY5", "ROX"]
        runningGraph.initCheckBox()

        posiList = []                                   // TODO: 根据样本信息获取PosiList
        var sampleInfo = CExpInfo.getSampleInfo(eid)
        for(let i = 0; i < sampleInfo.length; i ++){
            var r = sampleInfo[i]["RowNum"]
            var c = sampleInfo[i]["ColNum"]
            if(sampleInfo[i]["SampleName"]!=="" || sampleInfo[i]["SampleType"]!== "" || sampleInfo[i]["FAM"].toString()!=="0" || sampleInfo[i]["ROX"].toString()!=="0" || sampleInfo[i]["VIC"].toString()!=="0" || sampleInfo[i]["CY5"].toString()!=="0"){

                posiList.push(letters[r] + (Number(c)+1))
            }
        }
        posiFilter = posiList


        let res = CExpPro.checkIsCollect(equId)     // 是否采集
        if(res.toString() === "0"){
            isCollect = false
        }else{
            isCollect = true
        }

        // 刷新运行数据
        updateRunningInfo()
//        updateRunningChart()
    }


    // Private ===========================================================================
    property string equId: ""

    // 运行信息
    property real temperature: 95

    property string tempA: "0"
    property string tempB: "0"
    property string tempC: "0"
    property string tempD: "0"
    property string tempE: "0"
    property string tempF: "0"


    property int step: 3
    property int cycle: 33
    property int cycleNum: 42
    property string restTime: "--:--:--"
    property int clickNum: 0
    property bool isCollect: true

    // 图表信息
    property var accessFilter: []
    property var posiFilter: []
    property var posiList: []

    property bool isFullScreen: false


    property var letters: ["A","B","C","D","E","F","G","H","I","J","K"]

    Component.onDestruction: {
        console.log("RunningDisplay调用析构函数")
        timer.stop()
    }

    Timer{
        id: timer
        interval: 1000
        repeat: true
        triggeredOnStart: false
        onTriggered: {
            clickNum += 1
            if(clickNum % 1 === 0){
                if(!root.visible){
                    console.log("RunningDisplay隐藏")
                    timer.stop()
                }
                updateRunningInfo()
            }
        }

    }

    onVisibleChanged: {
        root.isFullScreen = false

        if(visible){
            timer.restart()
        }else{
            timer.stop()
        }
    }

    BoxTempture{
        id: boxTempture
    }

    function updateRunningInfo(){

        console.log("运行中 - 获取设备"+equId+"实时信息")
        var runningInfo = CExpPro.getOtherInfo(equId)



        var expStatus = runningInfo["ExpStatus"]
        var chartStatus = runningInfo["ChartStatus"]
//        console.log("expStatus"+expStatus+"  chartStatus"+chartStatus)

        if(expStatus === 1 || expStatus==="1"){ // 运行中
        }if(expStatus === 2 || expStatus === "2"){  // 结束实验-已完成
            root.experimentEnd()
            timer.stop()
            return
        }
        temperature = runningInfo["Temp"]
        cycle = runningInfo["Cycle"]
        cycleNum = runningInfo["CycleNum"]
        step = runningInfo["Step"]

        var res = CExpPro.getAllTempInfo(equId)
        tempA = res["TempOne"]
        tempB = res["TempTwo"]
        tempC = res["TempThree"]
        tempD = res["TempFour"]
        tempE = res["TempFive"]
        tempF = res["TempSix"]

        console.log("chartStatus:", chartStatus)
//        if(chartStatus.toString()==="1"){      // 有刷新数据时更新图表
        if(true){
            updateRunningChart()
        }


        // 剩余时间计算
        var startTime = runningInfo["RunTime"]
        var durTime = runningInfo["Duration"]
        var startH = ~~((startTime.split(" ")[1]).split(":")[0])
        var startM = ~~((startTime.split(" ")[1]).split(":")[1])
        var startS = ~~((startTime.split(" ")[1]).split(":")[2])

        startS = startH * 60*60 + startM * 60 + startS

        durTime = durTime.replace("时", ":")
        durTime = durTime.replace("分", ":")
        durTime = durTime.replace("秒", ":")
        var list = durTime.split(":")
        var durS = 0
        if(list.length === 4){
            durS = (~~list[0])*3600 + (~~list[1])*60 + (~~list[2])
        }else{
            durS = ~~list[0]*60 + ~~list[1]
        }
        var curTime = Qt.formatDateTime(new Date, "HH:mm:ss")
        var curH = ~~(curTime.split(":")[0])
        var curM = ~~(curTime.split(":")[1])
        var curS = ~~(curTime.split(":")[2])
        curS = curH * 60*60 + curM * 60 + curS

        restTime = startS + durS - curS
        var hhh = Math.floor(restTime/3600)
        var mmm = Math.floor((restTime%3600)/60)
        var sss = Math.floor(restTime%60)

        hhh = Math.max(0, hhh)
        mmm = Math.max(0, mmm)
        sss = Math.max(0, sss)      // 时间变成负的了……

        restTime = (hhh>=10?"":"0") + hhh + ":" +
                   (mmm>=10?"":"0") + mmm + ":" +
                   (sss>=10?"":"0") + sss

    }

    function updateRunningChart(){
        if(isCollect)
            runningGraph.refresh()

    }

    Connections{
        target: mainwindow
        onClosing:{
            console.log("监听到主窗口关闭，停止计时器")
            timer.stop()

        }
    }

    // 样式 ===============================================================================

    // 全屏显示属性
    x: isFullScreen ? -200*dp : 0
    y: isFullScreen ? -180*dp : 0
    height: isFullScreen ? mainwindow.height : parent.height
    width: isFullScreen ? mainwindow.width : parent.width


    BoxFilterRunning{
        id: boxFilterRunning
        onAccept: {
//            accessFilter = ["FAM", "VIC", "ROX", "CY5"]
//            updateRunningChart()
            runningGraph.updateCheckbox()       // 在RunningGraph里面调用updateRunningChart了（我这写的什么乱七八糟的东西）
        }
        onReject: {

        }
    }




    Item{       // 上面的温度
        id: layout_temp
        height: 80*dp
        width: root.width - 30*dp
        x: 15*dp
        y: 15*dp
        Row{
            spacing: 15*dp
            RunningInfoItem{
                width: layout_temp.width/4 - 15*dp
                title: "温度°C  (A区)"
                content: temperature
                imgSource: "qrc:/picture/running_tempture.png"
                Image{
                    height: 16*dp
                    width: 16*dp
                    x: 100*dp
                    y: 15*dp
                    source: "qrc:/picture/temperature_open.png"
                    MouseArea{
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        onReleased: {
                            boxTempture.show()
                        }
                    }
                    z: 1
                }
            }RunningInfoItem{
                width: layout_temp.width/4 - 15*dp
                title: "步骤(步)"
                content: step
                imgSource: "qrc:/picture/running_step.png"
            }RunningInfoItem{
                width: layout_temp.width/4 - 15*dp
                title: "循环"
                content: cycle.toString() + "/" + cycleNum.toString()
                imgSource: "qrc:/picture/running_cycle.png"
            }RunningInfoItem{
                width: layout_temp.width/4 - 15*dp
                title: "剩余时间"
                content: restTime
                imgSource: "qrc:/picture/running_time.png"
            }
        }
    }

    Rectangle{       // 图谱
        id: layout_graph
        height: root.height - 110*dp
        width: root.width
        y: 110*dp
        RunningGraph{
            id: runningGraph
            onFullScreen: {
                isFullScreen = !isFullScreen
            }
        }

    }


}
